#pragma Once
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include "Log.hpp"

enum
{
    SOCK_ERR = 1,
    BIND_ERR,
    LISTEN_ERR,

};

class Sock
{
public:
    void Socket()
    {
        socketfd = socket(AF_INET, SOCK_STREAM, 0);
        if (socketfd < 0)
        {
            lg(Fatal, "socket errno : %d ,%s", errno, strerror(errno));
            exit(SOCK_ERR);
        }

        int opt = 1; // 实现端口复用
        setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind(uint16_t &port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(socketfd, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind errno : %d ,%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        int n = listen(socketfd, 10);
        if (n < 0)
        {
            lg(Fatal, "listen errno : %d ,%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in remote;
        socklen_t len = sizeof(remote);

        int newfd = accept(socketfd, (struct sockaddr *)&remote, &len);
        if (newfd < 0)
        {
            lg(Warning, "accept errno : %d ,%s", errno, strerror(errno));
            return -1;
        }

        char buffip[64];
        inet_ntop(AF_INET, &remote.sin_addr, buffip, sizeof(buffip));
        *clientip = buffip;
        *clientport = ntohs(remote.sin_port);

        return newfd;
    }

    bool Connect(std::string &serverip, uint16_t &serverport)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
        int n = connect(socketfd, (const struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            lg(Warning, "connect errno : %d ,%s", errno, strerror(errno));
            return false;
        }

        return true;
    }

    int Getfd()
    {
        return socketfd;
    }

    void Close()
    {
        close(socketfd);
    }

private:
    int socketfd;
};